package cn.com.thinvent.dispatch.service.biz.impl;

import cn.com.thinvent.dispatch.dao.ShoppingCartMapper;
import cn.com.thinvent.dispatch.entity.ShoppingCart;
import cn.com.thinvent.dispatch.entity.response.PagedGridResult;
import cn.com.thinvent.dispatch.service.biz.ShoppingCartService;
import cn.com.thinvent.dispatch.service.biz.util.KeyGenerator;
import cn.com.thinvent.dispatch.service.biz.util.UserContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Component
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Resource
    private ShoppingCartMapper shoppingCartMapper;

    @Override
    public Integer addCarts(List<String> carts) {
        List<ShoppingCart> cartsByUserId = shoppingCartMapper.getCartsByUserId(UserContext.get());
        if(cartsByUserId.size() >= 10) {
            return -1;
        }
        if(cartsByUserId.size() <= 10) {
            boolean b = carts.size() > 10 - cartsByUserId.size();
            if(b) {
                return 10 - cartsByUserId.size();
            }
        }
        Date date = new Date();
        String username = UserContext.get();
        for (String cart : carts) {
            try {
                ShoppingCart shoppingCart = new ShoppingCart();
                shoppingCart.setId(KeyGenerator.generateKey());
                shoppingCart.setMenuId(cart);
                shoppingCart.setCreatedById(username);
                shoppingCart.setCreatedAt(date);
                shoppingCart.setUpdatedAt(date);
                shoppingCartMapper.insertCart(shoppingCart);
            } catch (Throwable throwable) {
                return -1;
            }
        }
        return 0;
    }

    @Override
    public PagedGridResult<ShoppingCart> getCartsByUserIdPaged(String createdById, int page, int pageSize) {
        int offset = (page - 1) * pageSize;
        List<ShoppingCart> carts = shoppingCartMapper.getCartsByUserIdPaged(createdById, pageSize, offset);
        int totalRecords = shoppingCartMapper.countCartsByUserId(createdById);
        int totalPages = (int) Math.ceil((double) totalRecords / pageSize);

        PagedGridResult<ShoppingCart> result = new PagedGridResult<>();
        result.setPage(page);
        result.setTotal(totalPages);
        result.setRecords(totalRecords);
        result.setRows(carts);

        return result;
    }

    @Override
    public int deleteByMenuIdAndCreatedById(String menuId, String createdById) {
        return shoppingCartMapper.deleteByMenuIdAndCreatedById(menuId, createdById);
    }
}
